import os
import sys

# 将工程目录加入包扫描
currPath = os.path.abspath(os.path.dirname(__file__))
srcPath = os.path.split(currPath)[0]
rootPath = os.path.split(srcPath)[0]
projectPath = os.path.split(rootPath)[0]
sys.path.append(projectPath)

from src.db.CcxDataCenterDb import CcxDataCenter
from src.db.LocalDb import LocalDb
from src.utils import BatchUtils
from src.utils.CommonUtils import cleanScreen
from operator import itemgetter
from itertools import groupby
import json
from src.utils.LogUtils import Logger


# 同步产业所有行业年度数据
class SyncIndustryAnnualData:
    def __init__(self):
        self.localDb = LocalDb(logSql=False, autocommit=True)
        self.dataCenterDb = CcxDataCenter(logSql=False, autocommit=True)

    def commonSql(self):
        CommonSql = """
            SELECT
                rad.credit_code,
                rad.`year` ,
                radd.`code` AS detailCode,
                radd.`value`,
                c.name,
                c.`options`
            FROM
                %s rad
                LEFT JOIN %s radd ON rad.id = radd.foreign_id
                left join %s c on radd.code =c.code 
            WHERE
                rad.ver = 0
              AND rad.`status` = 1
              AND rad.release_status = 1
              and c.release_status=1 and c.ver=0
            ORDER BY
                detailCode
        """
        return CommonSql

    def queryData(self, tableName, detailsName, targetName):
        sql = self.commonSql() % (tableName, detailsName, targetName)
        return self.dataCenterDb.Query(sql, None)

    def insertSql(self):
        sql = """
            INSERT INTO fin_enterprise_oper_data
                (credit_code, `year`, conent_text, update_time,resource_industry,resource_industry_name)
                VALUES('%s', %s, '%s', CURRENT_DATE(),'%s','%s');

        """
        return sql

    def deleteSql(self):
        sql = """
            DELETE FROM fin_enterprise_oper_data
            WHERE credit_code='%s' and year =%s and resource_industry= '%s'
        """
        return sql

    def convert(self, value, options):
        if value is None:
            return value
        optionList = json.loads(options)
        for item in optionList:
            if item["value"] == value:
                value = item["name"]
                return value
        return value

    def __insert__(self, data, industry, industryName):
        data.sort(key=itemgetter("credit_code"))
        for k, item in groupby(data, key=itemgetter('credit_code')):
            dataByCreditCode = list(item)
            dataByCreditCode.sort(key=itemgetter("year"))
            for i, n in groupby(dataByCreditCode, key=itemgetter('year')):
                result_tuple = []
                for s in list(n):
                    value = s["value"]
                    options = s["options"]
                    if options is not None and options != "":
                        # 遍历 转换
                        value = self.convert(value, options)
                    obj = {
                        "code": s["detailCode"],
                        "name": s["name"],
                        "value": value
                    }
                    result_tuple.append(obj)
                delete = self.deleteSql() % (k, i, industry)
                self.localDb.ExecNoneQuery(delete)
                sql = self.insertSql() % (k, i, json.dumps(result_tuple, ensure_ascii=False), industry, industryName)
                self.localDb.ExecNoneQuery(sql)
        return


data = {
    # 燃气行业
    "HY002": ["gas_annual_data", "gas_annual_data_detail", "gas_targets", "公用事业-燃气"],
    # 电力
    "HY003": ["electric_annual_data", "electric_annual_data_detail", "electric_targets", "电力"],

    # 房地产
    "HY005": ["real_estate_annual_data", "real_estate_annual_data_detail", "real_estate_targets", "房地产"],

    # 煤炭
    "HY006": ["coal_annual_data", "coal_annual_data_detail", "coal_targets", "煤炭"],

    # 有色金属
    "HY007": ["non_ferrous_metals_annual_data", "non_ferrous_metals_annual_data_detail", "non_ferrous_metals_targets",
              "有色金属"],

    # 钢铁
    "HY008": ["steel_company_annual_data", "steel_company_annual_data_detail", "steel_company_targets", "钢铁"],

    # 化工
    "HY009": ["chemical_annual_data", "chemical_annual_data_detail", "chemical_targets", "化工"],

    # 建筑
    "HY010": ["building_annual_data", "building_annual_data_detail", "building_targets", "建筑"],

    # 农林牧渔
    "HY012": ["agribusiness_annual_data", "agribusiness_annual_data_detail", "agribusiness_targets", "农林牧渔"],

    # 批发
    "HY014": ["wholesale_annual_data", "wholesale_annual_data_detail", "wholesale_targets", "批发和零售-批发"],

    # 医药
    "HY015": ["pharmaceutical_annual_data", "pharmaceutical_annual_data_detail", "pharmaceutical_targets", "医药"],

    # 装备制造
    "HY017": ["equipment_manufacturing_annual_data", "equipment_manufacturing_annual_data_detail",
              "equipment_manufacturing_targets", "装备制造"],

    # 港口
    "HY021": ["port_annual_data", "port_annual_data_detail", "port_targets", "港口"],

    # 机场
    "HY022": ["airport_annual_data", "airport_annual_data_detail", "airport_targets", "机场"],

    # 水务
    "HY027": ["water_annual_data", "water_annual_data_detail", "water_targets", "公用事业-水务"],

    # 批发和零售-零售
    "HY028": ["retail_annual_data", "retail_annual_data_detail", "retail_targets", "批发和零售-零售"],

    # 食品饮料
    "HY029": ["food_annual_data", "food_annual_data_detail", "food_targets", "轻工制造-食品饮料"],

    # 建筑材料-水泥
    "HY030": ["cement_annual_data", "cement_annual_data_detail", "cement_targets", "建筑材料-水泥"],

    # 建筑材料-其他建材
    "HY031": ["building_materials_annual_data", "building_materials_annual_data_detail", "building_materials_targets",
              "建筑材料-其他建材"],

    # 轻工制造-其他制造业
    "HY032": ["manufacture_annual_data", "manufacture_annual_data_detail", "manufacture_targets",
              "轻工制造-其他制造业"],

    # 交通运输-高速公路
    "HY033": ["freeway_annual_data", "freeway_annual_data_detail", "freeway_targets", "交通运输-高速公路"],

    # 交通运输-航空运输
    "HY034": ["airlift_annual_data", "airlift_annual_data_detail", "airlift_targets", "交通运输-航空运输"],

    # 汽车
    "HY035": ["car_annual_data", "car_annual_data_detail", "car_targets", "汽车"],

    # 综合
    "HY036": ["comprehensive_annual_data", "comprehensive_annual_data_detail", "comprehensive_targets", "综合"],

    # 其他交通运输业
    "HY037": ["transportation_other_annual_data", "transportation_other_annual_data_detail",
              "transportation_other_targets", "交通运输-其他"],
    # 电子
    "HY038": ["electronic_annual_data", "electronic_annual_data_detail", "electronic_targets", "电子"],
    # 通用行业
    "HY039": ["general_annual_data", "general_annual_data_detail", "general_targets", "通用"],
}


def main():
    cleanScreen()
    logger = Logger()
    sync = SyncIndustryAnnualData()
    total = len(data)
    perTotal = 0
    for item in data:
        item_ = data[item]
        result = sync.queryData(item_[0], item_[1], item_[2])
        if len(result) > 0:
            sync.__insert__(result, item, item_[3])
            #print("插入数据：", len(result), "条")
        perTotal = perTotal + 1
        logger.progress_bar("产业经营数据", perTotal, total)
    print("同步产业经营数据完成")


# 程序入口
if __name__ == "__main__":
    main()
